<?php

    /*  获取微信服务器access_token
     * 
     * author:zhao
     */
    function getToken(){
        $appid  = getenv('APPID');
        $secret = getenv('AppSecret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $token = file_get_contents($url);
        $token = json_decode($token,true);
        $token = $token['access_token'];
        return $token;
    }
    
    //获取微信服务器access_token  om18c0U6RuC5Ub2_X5nubCzNUvD8
    function getWxToken(){
        if(!file_exists(storage_path('app').'/token.txt')){
            $token = getToken();
            Storage::put('token.txt',$token);
        }else{
            $time = Storage::lastModified('token.txt'); 
            if((time()-$time) > 7200){
                $token = getToken();
                Storage::put('token.txt',$token);
            }else{
                $token = Storage::get('token.txt');
            } 
        }
        
        return $token;
    }
    
    //获取用户openid
    function getOpenId($code,$appid,$secret){
        $url  = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $info = file_get_contents($url);
        return $info;
    }
    
    function sendMessage(){
        $access_token = getWxToken();
        $data =array('touser'=>getOpenId(),'msgtype'=>'text','text'=>array('"content"=>"Hello World"'));
        $data = json_encode($data);
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
        $return = GoCurl($url,'POST',$data);
        return $return;
    }
    
    